package com.huang.config;

import com.huang.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

       //输出前端请求的token
        //System.out.println(request.getHeader("token"));
        //从去请求头中获得我们的token
        String token=request.getHeader("token");
        //验证token是否存在或过期
        if (token == null||"".equals(token)) {

            throw  new RuntimeException("请先登录在访问");
        }
       /* if (JwtUtils.isTokenExpired(token)) {
            System.out.println("令牌过时");
            throw  new RuntimeException("登录超时，请重新登录");
        }else {
            System.out.println("没有超时");
        }*/
        //基于负载信息查询用户信息和权限信息
        Claims claims=JwtUtils.getClaimsFromToken(token);
        //authorities是我们创建token的时候锁添加的用户权限信息的名字
        List<String> list=(List<String>) claims.get("authorities");
        //5.封装和存储认证和权限信息
        //5.1构建UserDetail对象(用户身份的象征-类似于一张名片,微信的二维码)

        UserDetails userDetails= User.builder()
                .username((String) claims.get("username"))
                .password("")
                .authorities(list.toArray(new String[]{}))
                .build();

        //5.2构建Security权限交互对象(记住,固定写法)
        PreAuthenticatedAuthenticationToken authToken=
                new PreAuthenticatedAuthenticationToken(
                        userDetails,//用户身份
                        userDetails.getPassword(),
                        userDetails.getAuthorities());
        //5.3将权限交互对象与当前请求进行绑定
        authToken.setDetails(new WebAuthenticationDetails(request));
        //5.4.将认证后的token存储到Security上下文(会话对象)
        SecurityContextHolder.getContext().setAuthentication(authToken);
        return true;
    }
}
